package edu.api.jdbc_api;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 封装的有对bs_user相关操作
 */
public class BsUserDao {

    static {
        //2. 注册驱动,将驱动实例注册到DriverManager
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Bs_user queryById(int id) throws SQLException {

        //sql拼接参数容易 出现 sql注入问题,可以通过占位符弥补
        String sql = "select * from bs_user where id = ?";
        List<Object> params = new ArrayList<>();
        params.add(id);
        ResultSet set = JDBCUtils.query(sql, params);
        Bs_user bs_user = null;
        while (set.next()){
            //根据字段的位置获取对应字段的数据
            int u_id = set.getInt(1);
            String username = set.getString(2);
            String psw = set.getString(3);
            //根据查询结果的字段名称
            String email = set.getString("email");
            String phone = set.getString("phone");
            String company = set.getString("company");
            //将数据进行封装
            bs_user = new Bs_user(u_id, username, psw, email, phone, company);
        }
        set.close();
        JDBCUtils.close();
        return bs_user;
    }

    public List<Bs_user> queryByUsername(String username) {
        String sql = "select * from bs_user where username like ?";
        return null;
    }

    public int deleteById(int id) throws SQLException {
        String sql = "delete from bs_user where id = ?";
        ArrayList<Object> list = new ArrayList<>();
        list.add(id);
        int i = JDBCUtils.update(sql, list);
        return i;
    }

    public int updateById(Bs_user bs_user) throws SQLException {
        String sql = "update bs_user set password = ? where username = ?";
        List<Object> params = new ArrayList<>();
        params.add(bs_user.getPassword());
        params.add(bs_user.getUsername());
        int i = JDBCUtils.update(sql, params);
        return i;
    }
}
